package com.wwh.furns.filter;

import com.google.gson.Gson;
import com.wwh.furns.entity.Member;
import com.wwh.furns.utils.WebUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Albert
 * @date 2024/8/10-20:29
 * @describe 用于权限验证，如果登录就放行
 */
public class AuthFilter implements Filter {
    private List<String> excludedUrls;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //获取到配置的excludedUrls
        String strExcludedUrls = filterConfig.getInitParameter("excludedUrls");
        String[] urls = strExcludedUrls.split(",");
        excludedUrls = Arrays.asList(urls);
        System.out.println(excludedUrls);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) servletRequest;
        String servletPath = req.getServletPath();
        System.out.println("请求的url = " + servletPath);

        Member member = (Member) req.getSession().getAttribute("member");

        if (!excludedUrls.contains(servletPath)) {
            if (member == null) {
                if (WebUtils.isAjaxRequest(req)) {
                    Map<String, Object> resultMap = new HashMap<>();
                    resultMap.put("url", "views/member/login.jsp");
                    String resultJson = new Gson().toJson(resultMap);
                    servletResponse.getWriter().write(resultJson);
                } else {
                    //转发不走过滤器
                    req.getRequestDispatcher("/views/member/login.jsp").forward(servletRequest, servletResponse);
                }
                return;
            } else if (!member.getUsername().equals("admin") && servletPath.contains("manage")) {
                System.out.println("权限不够！");
                req.getRequestDispatcher("/index.jsp").forward(servletRequest, servletResponse);
                return;
            }


        }

        filterChain.doFilter(servletRequest, servletResponse);

    }

    @Override
    public void destroy() {

    }
}
